import { filterAuth, findDicByCodeSort, getDicByKey } from '@/support/common';
import { transferOption } from '@/support/utils';
import { PlusOutlined } from '@ant-design/icons';
import { Card, message, Modal, Select, Tabs, Tag } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';

const { TabPane } = Tabs;
const tagColors = [
  'magenta',
  'red',
  'orange',
  'gold',
  'lime',
  'green',
  'cyan',
  'blue',
  'geekblue',
  'purple',
];
const mapStateToProps = (state: any) => ({
  dataPermission: state.dataPermission,
  loading: state.loading.effects['dataPermission/getData'],
});
class Detail extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      visible: false,
      selectVisible: false,
      sid: null,
      tabList: [],
      activeKey: null,
      newItems: [],
      dataList: [],
      originList: [],
      saveLoading: false,
      allOptionsMap: '',
      getOption: false,
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    if (this.context.dicData && JSON.stringify(this.context.dicData) != '[]') {
      this.getOptions(0, null);
    }
  }

  getOptions = (type: any, sid: any) => {
    this.props.dispatch({
      type: 'dataPermission/getData',
      payload: { url: '/datapermission/config/query' },
      callback: (res: any) => {
        let allOptionsMap = res.data ? new Map(Object.entries(res.data)) : new Map();
        let itemTypes = findDicByCodeSort(this.context.dicData, 'DPItemType');
        let tabList: any = [];
        itemTypes.map((item: any) => {
          if (allOptionsMap.get(item.dictKey)) {
            tabList.push(item);
          }
        });
        this.setState(
          {
            allOptionsMap: allOptionsMap,
            tabList: tabList,
            getOption: true,
          },
          () => {
            if (type == 1) {
              this.getItems(sid);
            }
          },
        );
      },
    });
  };

  getItems = (sid: any) => {
    const { tabList } = this.state;
    const { dispatch } = this.props;
    const key = tabList && tabList[0] ? tabList[0].dictKey : null;
    dispatch({
      type: 'dataPermission/getData',
      payload: { url: '/datapermission/finditemlist', sid: sid, itemType: key },
      callback: (res: any) => {
        let list: any = [];
        res.data.map((item: any) => {
          list.push(item.itemValue);
        });
        this.setState({
          sid: sid,
          dataList: list,
          originList: list,
        });
      },
    });
    this.setState({
      visible: true,
      activeKey: key,
    });
  };

  open = (sid: any) => {
    const { getOption } = this.state;
    if (getOption) {
      this.getItems(sid);
    } else {
      if (this.context.dicData && JSON.stringify(this.context.dicData) != '[]') {
        this.getOptions(1, sid);
      }
    }
  };

  close = () => {
    const { handleFlushPage } = this.props;
    this.setState(
      {
        visible: false,
        sid: null,
        selectVisible: false,
        newItems: [],
        dataList: [],
        originList: [],
        saveLoading: false,
      },
      () => {
        handleFlushPage();
      },
    );
  };

  save = () => {
    const { dispatch } = this.props;
    const { sid, activeKey, dataList } = this.state;
    const { handleFlushPage } = this.props;
    this.setState({ saveLoading: true });
    let param = {
      dataPermissionSid: sid,
      dataPermissionItemType: activeKey,
      permissionList: dataList,
    };
    dispatch({
      type: 'dataPermission/postObjWithRes',
      payload: { url: '/datapermission/config/add', ...param },
      callback: (res: any) => {
        this.setState({ saveLoading: false });
        if (res.statusCode === '0') {
          message.success('保存成功！');
          this.setState(
            {
              visible: false,
              sid: null,
              selectVisible: false,
              newItems: [],
              dataList: [],
              originList: [],
              saveLoading: false,
            },
            () => {
              handleFlushPage();
            },
          );
        }
      },
    });
  };

  onTabChange = (newActiveKey: any) => {
    const { dispatch } = this.props;
    const { sid, activeKey } = this.state;
    if (activeKey == newActiveKey) {
      return;
    }
    if (this.isEdited()) {
      message.warning(
        '请先保存' +
          getDicByKey(this.context.dicData, 'DPItemType', this.state.activeKey) +
          '权限！',
      );
    } else {
      dispatch({
        type: 'dataPermission/getData',
        payload: { url: '/datapermission/finditemlist', sid: sid, itemType: newActiveKey },
        callback: (res: any) => {
          let list: any = [];
          res.data.map((item: any) => {
            list.push(item.itemValue);
          });
          this.setState({
            dataList: list,
            originList: list,
          });
        },
      });
      this.setState({ activeKey: newActiveKey });
    }
  };

  onAddClick = () => {
    this.setState({ selectVisible: true }, () => {
      this.selectInstance.focus();
    });
  };

  onSelectChange = (values: any) => {
    this.setState({ newItems: values });
  };

  onSelectBlur = () => {
    const { newItems, dataList } = this.state;
    if (newItems == null || newItems.length == 0) {
      this.setState({ selectVisible: false });
    } else {
      this.setState({ selectVisible: false, dataList: dataList.concat(newItems), newItems: [] });
    }
  };

  handleClose = (removedTag: any) => {
    const tags = this.state.dataList.filter((tag: any) => tag !== removedTag);
    this.setState({ dataList: tags });
  };

  isEdited = () => {
    const { dataList, originList } = this.state;
    if (dataList.length != originList.length) {
      return true;
    }
    let compare = false;
    originList.map((origin: any) => {
      let flag = false;
      dataList.map((data: any) => {
        if (origin == data) {
          flag = true;
        }
      });
      if (!flag) {
        compare = true;
      }
    });
    return compare;
  };

  render() {
    const { loading, pathname } = this.props;
    const {
      visible,
      tabList,
      activeKey,
      selectVisible,
      dataList,
      saveLoading,
      allOptionsMap,
    } = this.state;
    let selectOptions: any = [];
    let optMap = new Map();
    if (activeKey && allOptionsMap) {
      let allOptions = allOptionsMap.get(activeKey);
      allOptions.map((item: any) => {
        let flag = false;
        dataList.map((data: any) => {
          if (data == item.dataPermissionItemValue) {
            flag = true;
          }
        });
        if (!flag) {
          selectOptions.push(item);
        }
        optMap.set(item.dataPermissionItemValue, item.dataPermissionItemLevel);
      });
    }
    const hasPermission = filterAuth('dataPermission_doConfig', this.context.permissions, pathname);
    return (
      <Modal
        centered
        visible={visible}
        onCancel={this.close}
        onOk={this.save}
        okText="保存"
        confirmLoading={saveLoading}
        cancelButtonProps={{ size: 'small' }}
        okButtonProps={{ size: 'small', disabled: !this.isEdited() }}
        width="50%"
        title="权限明细"
      >
        <Tabs activeKey={activeKey} tabPosition="left" size="small" onChange={this.onTabChange}>
          {tabList &&
            tabList.map((item: any) => {
              return (
                <TabPane tab={item.dictValue} key={item.dictKey}>
                  <Card
                    bordered={false}
                    size="small"
                    loading={loading}
                    bodyStyle={{ minHeight: 300, padding: '4px 0px' }}
                  >
                    {item.dictKey === activeKey ? (
                      <>
                        {dataList.map((item: any, index: any) => (
                          <Tag
                            style={{ marginBottom: 10 }}
                            key={item}
                            color={tagColors[index % 10]}
                            closable={hasPermission}
                            onClose={() => this.handleClose(item)}
                          >
                            <span style={{ fontSize: 16 }}>{optMap.get(item)}</span>
                          </Tag>
                        ))}
                        {!selectVisible &&
                          hasPermission &&
                          selectOptions &&
                          selectOptions.length > 0 && (
                            <Tag
                              style={{ background: '#fff', borderStyle: 'dashed' }}
                              onClick={this.onAddClick}
                            >
                              <span style={{ fontSize: 16 }}>
                                <PlusOutlined /> 新增
                              </span>
                            </Tag>
                          )}
                        {selectVisible && (
                          <Select
                            ref={(val: any) => (this.selectInstance = val)}
                            placeholder={'请选择' + item.dictValue}
                            mode="multiple"
                            size="small"
                            filterOption={(input: any, option: any) =>
                              option.props.children.indexOf(input) >= 0
                            }
                            style={{ minWidth: 120 }}
                            onBlur={this.onSelectBlur} //失去焦点时回调
                            onChange={this.onSelectChange}
                          >
                            {transferOption(selectOptions, [
                              'dataPermissionItemValue',
                              'dataPermissionItemLevel',
                            ])}
                          </Select>
                        )}
                      </>
                    ) : null}
                  </Card>
                </TabPane>
              );
            })}
        </Tabs>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(Detail);
